import { loginMd5 } from '@/api/user'
import { getToken, setToken, removeToken, setStorage, removeStorage, getStorage } from '@/utils/auth'
import { resetRouter } from '@/router'
import md5 from 'js-md5'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: getStorage('userName'),
    avatar: ''
  }
}

const state = getDefaultState()
// console.log(state, 'state')
const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { userName, password, verificationCode, uuid } = userInfo
    return new Promise((resolve, reject) => {
      loginMd5({ userName: md5(userName.trim()), password: md5(password), verificationCode: verificationCode, uuid: uuid }).then(response => {
        commit('SET_TOKEN', response.result.token)
        commit('SET_NAME', response.result.userName)
        // commit('SET_AVATAR', response.userName)
        setToken(response.result.token)
        setStorage('userName', response.result.userName)
        setStorage('userInfo', response.result)
        setStorage('status', response.result.status)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        removeToken() // must remove  token  first
        removeStorage('userName')
        removeStorage('userInfo')
        removeStorage('status')
        resetRouter()
        commit('RESET_STATE')
        resolve()
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

